import wx from 'labrador';
import CryptoJS from 'crypto-js';
import _ from 'lodash';
import { takeLatest } from 'redux-saga';
import { generateUUID } from '../utils/utils';
import { put, select } from 'redux-saga/effects';
// import { load } from '../redux/user';
import { getSessionKey, login, getCode, post, REQUEST_COMMENTARTICLE, REQUEST_UPLOAD_FORMID, commentPost } from '../service/mz.data.service';

const LOGIN_SUCCESS_MSG = '登录成功';
const LOGIN_ERROR_MSG = '登录失败';
const SEND_CODE_SUCCESS_MSG = '发送成功';
const SEND_CODE_ERROR_MSG = '发送失败';

const TYPE_WECHAT = 'wechat';
const uuid = generateUUID();

// 处理用户登录动作
function* handlerUserLoginAction(response) {
    if (response.status == 10000 && response.data.token) {
        // wx.showToast({ title: LOGIN_SUCCESS_MSG });
        yield put({ type: 'user/wechatLoginSuccess', payload: response.data });

        _.delay(() => {
            wx.navigateBack({ delta: 1 });
        }, 1000);
    } else if (response.status == 10001) {
        wx.showToast({ title: response.message });
    } else {
        wx.showToast({ title: LOGIN_ERROR_MSG });
    }
}


// 用户微信登录
export function* wechatLogin(action) {
    try {
        let wxUserInfo = action.payload;
        let wxLoginInfo = yield wx.login();
        let secret = yield getSessionKey({ code: wxLoginInfo.code });
        secret = JSON.parse(secret.data);
        if (secret.errcode) {
            wx.showToast({ title: LOGIN_ERROR_MSG });
            return;
        }
        let sessionKey = secret.session_key;
        let key = CryptoJS.enc.Base64.parse(sessionKey);
        let iv = CryptoJS.enc.Base64.parse(wxUserInfo.iv);
        let decrypted = CryptoJS.AES.decrypt(wxUserInfo.encryptedData, key, {
            iv: iv
        });
        let userInfo = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));

        let user = {
            nickname: wxUserInfo.userInfo.nickName,
            sex: wxUserInfo.userInfo.gender,
            headimgurl: wxUserInfo.userInfo.avatarUrl,
            unionid: userInfo.unionId
        };
        wx.showToast({
            icon: 'loading',
            duration: 1000
        });
        let response = yield login({
            user: user,
            type: TYPE_WECHAT,
            openid: secret.openid,
            uuid: uuid
        });
        yield handlerUserLoginAction(response);
    } catch (error) {
        // console.log(error);
        // wx.showToast({ title: LOGIN_ERROR_MSG });
    }
}

function* checkUserLoginStatus() {
    const user = yield select(x => x.user);
    if (!user || !user.token) {
        wx.navigateTo({ url: '/pages/login/index' });
        return false;
    }
    return true;
}

function* commentArticle(action) {
    const result = yield checkUserLoginStatus();

    if (result) {
        const data = yield commentPost(REQUEST_COMMENTARTICLE, action.payload);

        if (data) {
            yield put({ type: 'post/fetchComments', payload: { id: action.payload.id, pageNum: 0 } });
            wx.showToast({
                title: '评论成功～',
                duration: 1000
            });
            _.delay(() => {
                wx.navigateBack({ delta: 1 });
            }, 1000);
        }
    }
}

function* uploadFormId(action) {
    const result = yield checkUserLoginStatus();
    if (result) {
        yield post(REQUEST_UPLOAD_FORMID, action.payload);
    }
}

export function* userSagas() {
    yield takeLatest('user/checkLoginStatus', checkUserLoginStatus);
    yield takeLatest('user/wechatLogin', wechatLogin);
    yield takeLatest('user/commentArticle', commentArticle);
    yield takeLatest('user/uploadFormId', uploadFormId);
}